<?php
namespace Api\Controller\Center;

use Api\Controller\Message\MessageController;
use Api\Controller\Core\BaseController;
use XBCommon\XBCache;
use Fuyou\Fuiou;
use Admin\Controller\System\TokenHelperController;

class OrderController extends BaseController
{
    const T_MEMINFO = 'mem_info';
    const T_GOODS = 'goods';
    const T_MEMCOUPANS = 'mem_coupans';
    const T_CONTENTMANAGEMENT = 'sys_contentmanagement';
    const T_LOANSAPPLYLIST = 'loans_applylist';
    const T_LOANSXJAPPLYLIST = 'loans_xjapplylist';
    const T_LOANSPARAMETER = 'loans_parameter';//贷款参数设置
    const T_LOANSHKLIST = 'loans_hklist';

    public function _initialize()
    {
        parent::_initialize();
        $this->statusArr = array(
            '0' => '申请中',
            '1' => '放款中',//放款中
            '2' => '已放款',//已放款
            '3' => '已完成',
            '4' => '已取消',
            '5' => '已拒绝',
        );
    }
    /**
     * @功能说明: 立即借款校验(首页立即借款)
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/fastbuycheck
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"0"}
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function fastbuycheck()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        $retdata = array(
            'status' => '1',
            'msg' => '可以借款',
        );
        $meminfos = M(self::T_MEMINFO)->field('ForbidTime,Status,LimitBalcance')->find($mem['ID']);
		
        //判断是否认证，
        if ($meminfos['Status'] == '1') {
            $retdata['status'] = '0';
            $retdata['jumps'] = '2';
            $retdata['msg'] = '您还没有认证，请先去认证！';
            AjaxJson(0, 1, '您还没有认证，请先去认证！', $retdata, 1, $mem['KEY'], $mem['IV']);
        }
        //校验必须认证
        $checkflags = checkmust_renz($mem['ID']);
        if (!$checkflags) {
            $retdata['status'] = '0';
            $retdata['msg'] = '必须认证未认证完，请先去认证！';
            AjaxJson(0, 1, '必须认证未认证完，请先去认证！', $retdata, 1, $mem['KEY'], $mem['IV']);
        }
        //校验会员年龄有没有达到借款条件
        $membirthday = M('renzen_cards')->where(array('UserID' => $mem['ID'], 'Status' => '1', 'IsDel' => '0'))->getField('Birthday');
        if ($membirthday) {
            $membirthday = strtotime($membirthday);
            $memage = getage($membirthday);
            $MaxAges = get_basic_info('MaxAges');
            $MinAges = get_basic_info('MinAges');
            if ($memage < $MinAges || $memage > $MaxAges) {
                $err = '';
                AjaxJson(0, 0, '抱歉，您的年龄不符合条件！', $err, 1, $mem['KEY'], $mem['IV']);
            }
        }

        if (in_array($meminfos['Status'], array('3', '4'))) {
            $err = '';
            AjaxJson(0, 0, '您没有购买权限！', $err, 1, $mem['KEY'], $mem['IV']);
        }
        if ($meminfos['ForbidTime'] && $meminfos['ForbidTime'] > date('Y-m-d H:i:s')) {
            $retdata['status'] = '0';
            $retdata['ForbidTime'] = strtotime($meminfos['ForbidTime']) - time();
            $retdata['msg'] = $meminfos['ForbidTime'] . '之前，暂不能下单!';
        }
        //判断是否有未结束的 借款订单
        $orderinfos = M(self::T_LOANSAPPLYLIST)->where(array('UserID' => $mem['ID'], 'LoanStatus' => array('in', array('0', '1', '2')), 'IsDel' => '0'))->count('ID');
        if ($orderinfos) {
            $retdata['status'] = '0';
            $retdata['jumps'] = '1';
            $retdata['msg'] = '还有未完成的订单，暂不能下单!';
        }
        AjaxJson(0, 1, '恭喜您，数据校验成功！', $retdata, 1, $mem['KEY'], $mem['IV']);
    }
    /**
     * @功能说明: 获取借款金额与借款期限(我要借贷)
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/getjkparater
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"0"}
     *   gid 商品详情id
     * @返回信息: {'result'=>1,'message'=>'数据获取成功!'}
     */
    public function getjkparater()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        $LimitBalcance = M(self::T_MEMINFO)->where(array('ID' => $mem['ID']))->getField('LimitBalcance');
        //获取借款金额
        $moneylist = M(self::T_GOODS)->field('ID,SalePrice,Interest,Fastmoney,GuanliCost,CashCoupon')->where(array('SalePrice' => array('ELT', $LimitBalcance), 'IsShelves' => '1', 'IsDel' => '0'))->order('Sort asc,ID desc')->select();
        //获取借款期限
        $termlist = M('loans_term')->field('ID,NumDays,Applyfee,Fastmoney,GuanliCost')->where(array('Status' => '1', 'IsDel' => '0'))->order('Sort asc,ID desc')->select();
        $retdata = array(
            'moneylist' => $moneylist,
            'termlist' => $termlist,
        );	
//	    p($retdata);die;
        AjaxJson(1, 1, '恭喜您，数据校验成功！', $retdata, 1, $mem['KEY'], $mem['IV']);
    }
    /**
     * @功能说明: 到期应还金额(我要借贷)
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/gethkmoney
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"gid":"2","termid":"2","juanid":"2"}}
     *   gid 借款金额id   termid 借款期限id juanid 优惠劵id
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function gethkmoney()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        if (!$para['gid']) {
            AjaxJson(0, 0, '请选择借款金额！');
        }
        if (!$para['termid']) {
            AjaxJson(0, 0, '请选择借款期限！');
        }
        $LimitBalcance = M(self::T_MEMINFO)->where(array('ID' => $mem['ID']))->getField('LimitBalcance');
        $goodinfo = M(self::T_GOODS)->field('ID,SalePrice,Interest,CashCoupon')->where(array('ID' => $para['gid'], 'SalePrice' => array('ELT', $LimitBalcance), 'IsShelves' => '1', 'IsDel' => '0'))->find();
        if (!$goodinfo) {
            AjaxJson(0, 0, '借款金额信息异常！');
        }
        $terminfo = M('loans_term')->field('ID,Applyfee')->where(array('ID' => $para['termid'], 'Status' => '1', 'IsDel' => '0'))->find();
        if (!$terminfo) {
            AjaxJson(0, 0, '借款期限信息异常！');
        }
        //优惠劵信息校验
        if ($para['juanid'] != '0') {
            if ($goodinfo['CashCoupon'] == '2') {
                AjaxJson(0, 0, '此借款金额不能使用优惠劵！');
            }
            $coupaninfo = M(self::T_MEMCOUPANS)->field('ID,StartMoney,StartTime,Money')->where(array('ID' => $para['juanid'], 'UserID' => $mem['ID'], 'Isuser' => '1', 'IsDel' => '0', 'EndTime' => array('EGT', date('Y-m-d H:i:s'))))->find();
            if (!$coupaninfo) {
                AjaxJson(0, 0, '优惠劵信息异常！');
            }
            if ($goodinfo['SalePrice'] < $coupaninfo['StartMoney']) {
                AjaxJson(0, 0, '此借款金额不符合此优惠劵使用条件！');
            }
            if ($coupaninfo['StartTime'] > date('Y-m-d H:i:s')) {
                AjaxJson(0, 0, '此优惠劵暂不能使用！');
            }
        }
        //到期应还金额
        $hkmoney = '0';
        if ($coupaninfo) {
            $hkmoney = $goodinfo['SalePrice'] - $coupaninfo['Money'] + $goodinfo['Interest'] + $terminfo['Applyfee'];
        } else {
            $hkmoney = $goodinfo['SalePrice'] + $goodinfo['Interest'] + $terminfo['Applyfee'];
        }
        $retdata = array(
            'hkmoney' => $hkmoney,
        );
        AjaxJson(0, 1, '恭喜您，数据校验成功！', $retdata);
    }
//	扣款函数
//$status  功能id
//1 身份认证
//2银行卡认证
//3基本信息认证
//4社交认证
//5支付宝认证
//6手机认证
//7淘宝认证
    public function koukuan($status = '0')
    {
//	    $url = "http://php.51xjsd.com/admin.php/admin/login/koukuan";//连接地址       
//		$username='123456';//账号
//		$password='123456';//密码
//		$password=md5($password);
//   	$data=$this->mmma($username,$password);
//		$data['status']=$status;
////		p($data);
//		$re=httpPost($data, $url);
//		$re=json_decode($re,1);
////		p($re);
//      if($re['status']!==1){
//			AjaxJson(0,0,'系统错误 ，请联系官方');
//      }
        return true;
    }
   ///  生成token
    public function mmma($username, $password)
    {
        $data['username'] = $username;
        $data['password'] = $password;
        $data['token'] = md5($username . md5($password));
        return $data;
    }
	//	雷达
    public function xinyan($datainfo)
    {
// 	 	$re=$this->koukuan(8);//扣款创建订单
//     	if(!$re){
//      	AjaxJson(0,0,'系统错误 ，请联系官方');
//      }
        $url = 'http://app.51xjsd.cn/Radar-report/controllers/CreditRadarController.php';
        $data['urlType'] = 'json';//版本号
        $data['versions'] = '1.3.0';//版本号
        $data['url'] = 'https://api.xinyan.com/product/radar/v3/report';//版本号
        $data['id_no'] = $datainfo['id_no'];//被查询人身份证号
        $data['id_name'] = $datainfo['id_name'];//姓名
        $data['phone_no'] = $datainfo['phone_no'];//手机号
        $data['bankcard_no'] = $datainfo['bankcard_no'];//银行卡号
        $data['trans_id'] = $datainfo['trans_id'];//新颜商户号 跟端口号一样
//		
//		p($data);die;
        $re = httpPost($data, $url);
        $re = json_decode($re, 1);
//		p($re);die;
        return $re;
    }
// 负面洗白
    public function fumianxibai($datainfo)
    {
//  	$re=$this->koukuan(10);//扣款创建订单
//     	if(!$re){
//      	AjaxJson(0,0,'系统错误 ，请联系官方');
//      }
        $url = 'http://app.51xjsd.cn/Radar-report/controllers/CreditRadarController.php';
        $data['urlType'] = 'json';//版本号
        $data['versions'] = '1.3.0';//版本号
        $data['url'] = 'https://api.xinyan.com/product/negative/v3/white';//版本号
//		$data['id_no']='340822199206114339';//被查询人身份证号

        $data['id_no'] = $datainfo['id_no'];//被查询人身份证号
        $data['id_name'] = $datainfo['id_name'];//姓名
        $data['phone_no'] = $datainfo['phone_no'];//手机号
        $data['bankcard_no'] = $datainfo['bankcard_no'];//银行卡号
        $data['trans_id'] = $datainfo['trans_id'];//新颜商户号 跟端口号一样
		
//		p($data);die;
        $re = httpPost($data, $url);
        $re = json_decode($re, 1);
        return $re;

    }
// 负面拉黑
    public function fumianlahei($datainfo)
    {
        $url = 'http://app.51xjsd.cn/Radar-report/controllers/CreditRadarController.php';
        $data['urlType'] = 'json';//版本号
        $data['versions'] = '1.3.0';//版本号
        $data['url'] = 'https://api.xinyan.com/product/negative/v3/black';//版本号
//		$data['id_no']='340822199206114339';//被查询人身份证号

        $data['id_no'] = $datainfo['id_no'];//被查询人身份证号
        $data['id_name'] = $datainfo['id_name'];//姓名
        $data['phone_no'] = $datainfo['phone_no'];//手机号
        $data['bankcard_no'] = $datainfo['bankcard_no'];//银行卡号
        $data['trans_id'] = $datainfo['trans_id'];//新颜商户号 跟端口号一样
        $re = httpPost($data, $url);
        $re = json_decode($re, 1);
        return $re;

    }
    /**
     * @功能说明: 提交订单操作(我要借贷)  安卓
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/downorder
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"gid":"2","termid":"2","juanid":"2"}}
     *   gid 借款金额id   termid 借款期限id juanid 优惠劵id
     * @返回信息: {'result'=>1,'message'=>'数据获取成功!'}
     */
    public function downorder()
    {	
//		echo 333;die;

        $para = get_json_data();//接收参数
//      \Think\Log::record('songsong');
//		$para12=json_encode($para);
//      \Think\Log::record($para12);
//      p($para);die;
        $mem = getUserInfo(get_login_info('ID'));
//		p($mem);die;
        $ressssss = M('loans_applylist')->where(['UserID' => $mem['ID'], 'LoanStatus' => '6'])->find();
        if ($ressssss) {
            AjaxJson(0, 0, '有正在执行的订单 ，请勿重复提交');//判断是否有正在等待银行打款的订单
        }
        $ressssss = M('loans_applylist')->where(['UserID' => $mem['ID'], 'LoanStatus' => '7'])->find();
        if ($ressssss) {
            AjaxJson(0, 0, '有正在执行的订单 ，请及时联系客服');//判断是否有正在等待银行打款的订单
        }
		//获取用户最新一条被拒绝的订单并判断是否在被拒绝的日期后申请，不是便拒绝申请
        $where['UserID'] = $mem['ID'];
        $where['Status'] = 2;
        $orderInfo = M('loans_applylist')->where($where)->order('ShTime desc')->find();
        if ($orderInfo) {
            $rejectTime = strtotime("{$orderInfo['ShTime']} +{$orderInfo['ForbidDay']} day");
            $nextTime = date('Y-m-d H:i:s', $rejectTime);
            if ($rejectTime >= time()) {
                AjaxJson(0, 0, "由于上次被拒绝，需{$nextTime}后可再次申请");
            }
        }
        //校验
        if (!$para['gid']) {
            AjaxJson(0, 0, '请选择借款金额！');
        }
        if (!$para['termid']) {
            AjaxJson(0, 0, '请选择借款期限！');
        }
        //校验 是否有借款的条件
        $rtdata = checkmembuy($mem['ID']);
        if ($rtdata['result'] == '0') {
            AjaxJson(0, 0, $rtdata['message']);
        }
        //校验必须认证
        $checkflags = checkmust_renz($mem['ID']);
        if (!$checkflags) {
            AjaxJson(0, 0, '必须认证未认证完，请先去认证！');
        }
        //校验会员年龄有没有达到借款条件
        $membirthday = M('renzen_cards')->where(array('UserID' => $mem['ID'], 'Status' => '1', 'IsDel' => '0'))->getField('Birthday');
        if ($membirthday) {
            $membirthday = strtotime($membirthday);
            $memage = getage($membirthday);
            $MaxAges = get_basic_info('MaxAges');
            $MinAges = get_basic_info('MinAges');
            if ($memage < $MinAges || $memage > $MaxAges) {
                AjaxJson(0, 0, '抱歉，您的年龄不符合条件！');
            }
        }
        //获取会员的借款额度
        $LimitBalcance = M(self::T_MEMINFO)->where(array('ID' => $mem['ID']))->getField('LimitBalcance');
//		P($LimitBalcance);
        $goodinfo = M(self::T_GOODS)->field('ID,SalePrice,Interest,Fastmoney,GuanliCost,CashCoupon')->where(array('ID' => $para['gid'], 'SalePrice' => array('ELT', $LimitBalcance), 'IsShelves' => '1', 'IsDel' => '0'))->find();
        if (!$goodinfo) {
            AjaxJson(0, 0, '借款金额信息异常！');
        }
        $terminfo = M('loans_term')->field('ID,NumDays,Applyfee,Fastmoney,GuanliCost')->where(array('ID' => $para['termid'], 'Status' => '1', 'IsDel' => '0'))->find();
        if (!$terminfo) {
            AjaxJson(0, 0, '借款期限信息异常！');
        }
        //优惠劵信息校验
        if ($para['juanid'] != '0') {
            if ($goodinfo['CashCoupon'] == '2') {
                AjaxJson(0, 0, '此借款金额暂不支持使用优惠劵！');
            }
            $coupaninfo = M(self::T_MEMCOUPANS)->field('ID,StartMoney,StartTime,Money')->where(array('ID' => $para['juanid'], 'UserID' => $mem['ID'], 'Isuser' => '1', 'IsDel' => '0', 'EndTime' => array('EGT', date('Y-m-d H:i:s'))))->find();
            if (!$coupaninfo) {
                AjaxJson(0, 0, '优惠劵信息异常！');
            }
            if ($goodinfo['SalePrice'] < $coupaninfo['StartMoney']) {
                AjaxJson(0, 0, '此借款金额不符合此优惠劵使用条件！');
            }
            if ($coupaninfo['StartTime'] > date('Y-m-d H:i:s')) {
                AjaxJson(0, 0, '此优惠劵暂不能使用！');
            }
        }

        //提交借款申请
        $hkmoney = '0';//到期应还金额
        if ($coupaninfo) {
            $hkmoney = $goodinfo['SalePrice'] - $coupaninfo['Money'] + $goodinfo['Interest'] + $terminfo['Applyfee'];
        } else {
            $hkmoney = $goodinfo['SalePrice'] + $goodinfo['Interest'] + $terminfo['Applyfee'];
        }
        $model = M();
        $model->startTrans();//事物开始进行数据库 操作
        $paraterinfos = M(self::T_LOANSPARAMETER)->find();//贷款参数
        //提交借款申请
        $OrderSn = date(ymd) . rand(1, 9) . date(His) . rand(111, 999);
        $AdoptMoney = $goodinfo['Fastmoney'] + $terminfo['Fastmoney'];//快速申请费
        $FJMoney = $goodinfo['GuanliCost'] + $terminfo['GuanliCost'];//用户管理费
        $Interest = $goodinfo['Interest'] + $terminfo['Applyfee'];//利息
        
        if($para['ip']=='0.0.0.0'){
        	$para['ip']='';
        }
		 if($para['wifi']=='unknown ssid'){
        	$para['wifi']='';
        }
        $applydata = array(
            'UserID' => $mem['ID'],
            'ApplyTime' => date('Y-m-d H:i:s'),
            'OrderSn' => $OrderSn,
            'LoanNo' => $OrderSn,
            'ApplyMoney' => $goodinfo['SalePrice'],
            'AdoptMoney' => $AdoptMoney,
            'FJMoney' => $FJMoney,
            'Interest' => $Interest,
            'ApplyDay' => $terminfo['NumDays'],
            'ProductID' => $goodinfo['ID'],
            'OpenM' => $goodinfo['SalePrice'] - $AdoptMoney - $FJMoney,
            'BackM' => $hkmoney,
            'RongDay' => $paraterinfos['RongDay'],
            'RongP' => $paraterinfos['RongP'],
            'OverdueDay' => $paraterinfos['OverdueDay'],
            'OverdueP' => $paraterinfos['OverdueP'],
            'ip'=>$para['ip'],
            'wifi'=>$para['wifi'],
        );
		
//	p($applydata);die;
//		统计借款次数   
	   $jkuannumbs = M('loans_applylist')->where(['UserID'=>$mem['ID']])->count('ID');
        if (!$jkuannumbs) {
        	$is_fujie='0';
            $jkuannumbs = '0';
        }else{
        	$is_fujie='1';
        }
		$applydata['LoanSum']=$jkuannumbs+1;
		$applydata['is_fujie']=$is_fujie;
        if ($coupaninfo) {
            //使用了优惠劵
            $applydata['CouponID'] = $coupaninfo['ID'];
            $applydata['CoMoney'] = $coupaninfo['Money'];
        }
        //分配客服
        $kefudata = getkefudata($mem['ID']);
        if ($kefudata['kfid']) {
            $applydata['SqAdminID'] = $kefudata['kfid'];//专属客服
			$applydata['ServiceID'] = $kefudata['kfid'];//订单客服
        }else{
//      $caiwulist=M('sys_administrator')->field('ID')->where(['RoleID'=>'7','IsDel'=>'0','Status'=>'1'])->select();
//		$key = rand(0,(int)(count($caiwulist)-1));
//		$applydata['SqAdminID'] = $caiwulist[$key]['ID'];//专属客服
//		$applydata['ServiceID'] = $caiwulist[$key]['ID'];//订单客服
		
        }
//      if ($kefudata['fkid']) {
//          $applydata['FKadminID'] = $kefudata['fkid'];
//      }
        if ($kefudata['csid']) {
            $applydata['CsadminID'] = $kefudata['csid'];
        }
//		p($applydata);die;
        $result2 = $model->table('xb_loans_applylist')->add($applydata);	
		
//$result2='1';
//		P($result2);DIE;
        if ($result2) {
        $model->commit();//这个提交开启就可以添加申请订单
//		规则验证@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//		获取有盾数据getField('Yddatas')
		$mobileinfos=M('renzen_cards')->where(array('UserID'=>$mem['ID']))->getField('Yddatas');//有盾数据
	    $mobileinfos=unserialize($mobileinfos);
		$yuyinghsangba=M('renzen_mobile')->where(array('UserID'=>$mem['ID']))->getField('baogao');//运营商 报告数据
		$yuyinghsangba=json_decode($yuyinghsangba,1);
		$yuyinghsangyuanshi=M('renzen_mobile')->where(array('UserID'=>$mem['ID']))->getField('CallBill');//运营商源是数据
		$yuyinghsangyuanshi=json_decode($yuyinghsangyuanshi,1);
//		p($yuyinghsangba);die;
		$tabaobg=M('renzen_taobao')->where(array('UserID'=>$mem['ID']))->getField('Receivers');//淘宝
		$tabaobg=json_decode($tabaobg,1);
		
//		p($tabaobg);die;
		$zhimafen=M('renzen_taobao')->where(array('UserID'=>$mem['ID']))->getField('zhimafen');//芝麻分
		//		获取手机通讯录
            $Phonelist=M('renzen_social')->where(array("UserID"=>$mem['ID']))->getField('Phonelist');
            if($Phonelist){
              $Phonelist=unserialize($Phonelist);
				$Phonelist=remove_duplicate($Phonelist);
				$Phonelistcount=count($Phonelist);
            }
//			淘宝报告数据
			$TaskID=M('renzen_taobao')->where(array('UserID'=>$mem['ID']))->getField('TaskID');//淘宝
            $token=M('sys_inteparameter')->where(['ParaName'=>'tokenmoxie'])->getField('ParaValue');
		    $taobaobaogao=taobao_renzhenbaogao($TaskID,$token);	//获取淘宝认证数据
            $taobaobaogao=json_decode($taobaobaogao,1);
//			p($taobaobaogao);die;
            $mem_info=M('mem_info')->where(array('ID'=>$mem['ID']))->find();//获取注册表信息
//获取过去一小时同一密码注册个数	
		    $timeend=date('Y-m-d h:i:s',time());
		    $timestart=date('Y-m-d h:i:s',time()-86400);
//			p($timeend);
//			p($timestart);
			$ccctime['RegTime']=array('between',array($timestart,$timeend));
			$ccctime['Password']=$mem_info['Password'];
//			P($ccctime);DIE;
		    $countmima=M('mem_info')->where($ccctime)->count();
			$inxi['mima']=$countmima;  
//		        一个月内同一手机哈注册数
		    $timestartmobile=date('Y-m-d h:i:s',time());
		    $timeendmobile=date('Y-m-d h:i:s',time()-86400*30);
		    $ccctimemobile['RegTime']=array('between',array($timeendmobile,$timestartmobile));
			$ccctimemobile['Mobile']=$mem_info['Mobile'];
//			$ccctimemobile['Mobile']='15239626761';
		    $countmobile=M('mem_info')->where($ccctimemobile)->count();
            $inxi['mobile']=$countmobile;  
//			12*同一设备号注册手机号数量>=3，则拒贷
            $countDeviceToken=M('mem_info')->where(['DeviceToken'=>$mem_info['DeviceToken']])->count();
            $inxi['DeviceToken']=$countDeviceToken;
//			13*3日内，同一ip地址的申请数量>5,则拒贷


            $timestarip=date('Y-m-d H:i:s',time());
		    $timendip=date('Y-m-d H:i:s',time()-86400*3);
		    $ccctimeip['ApplyTime']=array('between',array($timendip,$timestarip));
			$ccctimeip['ip']=$para['ip'];
			
			
//			p($ccctimeip);
            $countIP=M('loans_applylist')->where($ccctimeip)->count();
            $inxi['ip']=$countIP;
		   //14*同一位置下累计申请>10个客户，则拒贷
		
		
//      15*3日内，同一wifi名称的申请数>5,则拒贷 
            $timestarwifi=date('Y-m-d H:i:s',time());
		    $timendwifi=date('Y-m-d H:i:s',time()-86400*3);
		    $ccctimewifi['ApplyTime']=array('between',array($timendwifi,$timestarwifi));
			$ccctimewifi['wifi']=$para['wifi'];
			
//			p($ccctimewifi);
            $countwifi=M('loans_applylist')->where($ccctimewifi)->count();
            $inxi['wifi']=$countwifi;
//			p($inxi);die;
//          16*1天内同一设备注册次数>=5
            $timestarshebei=date('Y-m-d h:i:s',time());
		    $timendshebei=date('Y-m-d h:i:s',time()-86400);
		    $ccctimeshebei['ApplyTime']=array('between',array($timendshebei,$timestarshebei));
			$ccctimeshebei['wifi']=$para['wifi'];
            $countsehbei=M('loans_applylist')->where($ccctimeshebei)->count();
            $inxi['shebei']=$countwifi;
//      19*同一账号本次登录IP不是上次登录IP且本次登录设备不是上次登录设备 
//	    20*同一设备上借款的手机号>=3 				
//		21*同一手机号借款的设备数>=3 		
//	    22*同一身份证号借款的设备数>=3 
//		23*同一设备借款的身份证号>=3 
//			p($inxi);die;
		//新颜雷达$xinyanar
		//负面洗白$fumianxibaiar
		//有盾$mobileinfos
		//负面拉黑$fumianlaheiar
		//淘宝认证报告 $tabaobg
		//运营商yuyinghsangba
		//芝麻分$zhimafen
//		获取手机通讯录个数$num
//      运营商原始数据$yuyinghsangyuanshi 
//不重复通讯录人数<10人，$Phonelistcount
//淘宝报告数据
		 $UserID=M('loans_applylist')->where(array("ID"=>$result2))->getField('UserID');
         $Phonelist=M('renzen_social')->where(array("UserID"=>$UserID))->getField('Phonelist');
         if($Phonelist){
                $Phonelist=unserialize($Phonelist);
                $num=count($Phonelist);
          }
//		p($num);die;

		$guize=$this->guize($xinyanar,$fumianxibaiar,$mobileinfos,$fumianlaheiar,$tabaobg,$yuyinghsangba,$zhimafen,$num,$yuyinghsangyuanshi,$Phonelistcount,$taobaobaogao,$inxi);
//		 p($guize);die;
		 if(!$guize['res']){
		 	$restijiao=M('loans_applylist')->where(['ID'=>$result2])->save(['guize'=>'1','guize_mass'=>$guize['mass']]);
		 	$time='1';     
			if($restijiao){
		 	 AjaxJson(0,1,'请等待审核！',$time);
			}     
		 }else{
		 	$restijiao=M('loans_applylist')->where(['ID'=>$result2])->save(['guize'=>'0','guize_mass'=>$guize['mass']]);
		 	$time='1';     
			if($restijiao){
		 	 AjaxJson(0,1,'初审已经通过  请等待人工审核！！',$time);
			}
		 }
       } else {
            $model->rollback();
			$time = '1';//返回一个时间让前端做延时处理
            AjaxJson(0, 0, '申请提交失败！', $time);
           
        }
    }
//规则
    public function guize($data1, $data2, $data3, $data4, $data5, $data6, $data7,$num,$data8,$data9,$data10,$inxi)
    {
		 $data=M('ss_guize_leida')->find();  //获取规则配置
		//新颜雷达$xinyanar
		//负面洗白$fumianxibaiar
		//有盾$mobileinfos
		//负面拉黑$fumianlaheiar
		//淘宝认证报告 tabaobg
		//运营商yuyinghsangba
        //芝麻分  $芝麻分
        //通讯录个数
//      运营商原始数据
//不重复通讯录人数
//淘宝报告数据
//		P($data1);
//		P($data2);
//		P($data3);
//		P($data4);
//		P($data5);
//	 	P($data6);
//	    P($data7);
//      P($num);
//      P($data8);
//$Phonelistcount
//运营商数据判断
//p($data6['basic_check_items']);
//p($data6);
//var_dump($data5);die;
//die;
//入网时长
//p($data);die;
//		有盾分值判断
			if($data3['ud_order_no']){
	//			高风险
				if($data3['score_detail']['score']>$data['ss_100']){
					if($data['ss_100_status']==2){
					   $re['res']='0';
				$re['mass']='A01';
				return $re; 
					}
				}
	//			总申请借款平台数
				if($data3['loan_detail']['loan_platform_count']>$data['ss_101']){
					if($data['ss_101_status']==2){
					   $re['res']='0';
				$re['mass']='A02';
				return $re;
					}
				}
	////			实际借款平台数
				if($data3['loan_detail']['actual_loan_platform_count']>$data['ss_102']){
					if($data['ss_102_status']==2){
					  $re['res']='0';
				$re['mass']='A03';
				return $re;
					}
				}
				
	////			命中作弊软件
				if($data3['device_detail']['cheats_device']>0){
					if($data['ss_103_status']==2){
					   $re['res']='0';
				$re['mass']='A04';
				return $re; 
					}
				}
	////			命中安装极多借款app   这里判定大于三个 视为命中
	            if($data3['device_detail']['app_instalment_count']>3){
					if($data['ss_104_status']==2){
					   $re['res']='0';
				$re['mass']='A05';
				return $re;
					}
				}

	////			命中法院失信黑名单>
				if($data3['graph_detail']['link_user_detail']['court_dishonest_count']){
					if($data['ss_105_status']==2){
					  $re['res']='0';
				$re['mass']='A06';
				return $re;
					}
				}
	////命中网贷失信黑名单>
				if($data3['graph_detail']['link_user_detail']['online_dishonest_count']){
					if($data['ss_106_status']==2){
					   $re['res']='0';
				$re['mass']='A07';
				return $re; 
					}
				}
				
//				关联用户数大于

//p($data3['graph_detail']['link_user_count']);
//p($data['ss_107']);die;
				if($data3['graph_detail']['link_user_count']>$data['ss_107']){
					if($data['ss_107_status']==2){
					   $re['res']='0';
				$re['mass']='A08';
				return $re; 
					}
				}
//				关联设备数大于
				if($data3['graph_detail']['other_link_device_count']>$data['ss_108']){
					if($data['ss_108_status']==2){
					   $re['res']='0';
				$re['mass']='A09';
				return $re; 
					}
				}
				
				
//				10*风险地区限制拒贷 新疆，西藏，青海，海南，海口，乌鲁木齐，拉萨，西宁，盐源，宁海，建德，泰顺，苍南，六盘水，毕节 

				$arrayName = array('新疆','西藏' ,'海南');
//				*11风险地区限制拒贷 内蒙古(民族不是汉族)、贵州(民族不是汉族)、云南(民族不是汉族
				if($data['ss_1019_status']==2){
                        $addres=mb_substr($data3['id_detail']['address'], 0,2,'utf-8');
						if(in_array($addres, $arrayName)){
						   $re['res']='0';
					       $re['mass']='A10';
					       return $re; 
						}
				  
				}
//先不做


//				p($data3['id_detail']);
				$arrayName = array('内蒙','贵州' ,'云南');
//				*11风险地区限制拒贷 内蒙古(民族不是汉族)、贵州(民族不是汉族)、云南(民族不是汉族
				if($data['ss_1010_status']==2){
					if($data3['id_detail']['nation']!='汉'){
                        $addres=mb_substr($data3['id_detail']['address'], 0,2,'utf-8');
						if(in_array($addres, $arrayName)){
						   $re['res']='0';
					       $re['mass']='A11';
					       return $re; 
						}
				    }
				}
				
//12*同一设备号注册手机号数量>=3
if($inxi['DeviceToken']>$data['ss_1011']){
	if($data['ss_1011_status']==2){
		$re['res']='0';
		$re['mass']='A12';
	    return $re; 
	}
}

////13*3日内，同一ip地址的申请数量>5,则拒贷 
//if($inxi['ip']>$data['ss_1012']){
//	if($data['ss_1012_status']==2){
//		$re['res']='0';
//		$re['mass']='A13';
//	    return $re; 
//	}
//}
//14*同一位置下累计申请>10个客户，则拒贷
//15*3日内，同一wifi名称的申请数>5,则拒贷 

//if($inxi['wifi']>$data['ss_1014']){
//	if($data['ss_1014_status']==2){
//		$re['res']='0';
//		$re['mass']='A15';
//	    return $re; 
//	}
//}


//16*1天内同一设备注册次数>=5

if($inxi['shebei']>$data['ss_1015']){
	if($data['ss_1015_status']==2){
		$re['res']='0';
		$re['mass']='A16';
	    return $re; 
	}
}
//17*1月内同一手机号注册次数>
if($inxi['mobile']>$data['ss_1016']){
	if($data['ss_1016_status']==2){
		$re['res']='0';
		$re['mass']='A17';
	    return $re; 
	}
}
//18*1小时内同一密码注册次数>=10 
if($inxi['mima']>$data['ss_1017']){
	if($data['ss_1017_status']==2){
		$re['res']='0';
		$re['mass']='A18';
	    return $re; 
	}
}
//      19*同一账号本次登录IP不是上次登录IP且本次登录设备不是上次登录设备 
//	    20*同一设备上借款的手机号>=3 				
//		21*同一手机号借款的设备数>=3 		
//	    22*同一身份证号借款的设备数>=3 
//		23*同一设备借款的身份证号>=3 
	}	

//淘宝
		//		芝麻分
		if($data7<$data['taobao_1']){
			if($data['taobao_1_status']==2){
				$re['res']='0';
				$re['mass']='B01';
				return $re;
					 
				}
		}
		//该用户的淘宝VIP值；vip值约等于购物金额小于
		if($data5['userinfo']['vip_count']<$data['taobao_2']){
			if($data['taobao_2_status']==2){
					$re['res']='0';
				$re['mass']='B02';
				return $re;
				}
		}
//		vip等级	无等级(-1)和0～6级
		if($data5['userinfo']['vip_level']<$data['taobao_3']){
			if($data['taobao_3_status']==2){
					 $re['res']='0';
				$re['mass']='B03';
				return $re;
				}
		}
//		天猫等级
		if($data5['userinfo']['tmall_level']<$data['taobao_4']){
			if($data['taobao_4_status']==2){
					$re['res']='0';
				$re['mass']='B04';
				return $re;
				}
		}
//		淘气值
		if($data5['userinfo']['tao_score']<$data['taobao_5']){
			if($data['taobao_5_status']==2){
					 $re['res']='0';
				$re['mass']='B05';
				return $re;
				}
		}
		//		是否认证
		if(!$data5['userinfo']['account_auth']){
			if($data['taobao_6_status']==2){
					 $re['res']='0';
				$re['mass']='B06';
				return $re;
				}
		}
//		淘宝关联支付宝
//		账户余额  支付宝
		if($data5['alipaywealth']['balance']/100<$data['zhifubao_1']){
//			p($data5['alipaywealth']['balance']/100);die;
			if($data['zhifubao_1_status']==2){
					 $re['res']='0';
				$re['mass']='B07';
				return $re; 
				}
		}
//		余额宝累计收益
		if($data5['alipaywealth']['total_profit']/100<$data['zhifubao_2']){
			
			if($data['zhifubao_2_status']==2){
					 $re['res']='0';
				$re['mass']='B08';
				return $re; 
				}
		}
//		余额宝金额
		if($data5['alipaywealth']['total_quotient']/100<$data['zhifubao_3']){
			if($data['zhifubao_3_status']==2){
					 $re['res']='0';
				$re['mass']='B09';
				return $re; 
				}
		}
		//	花呗授信额度
		if($data5['alipaywealth']['huabei_totalcreditamount']/100<$data['zhifubao_4']){
			if($data['zhifubao_4_status']==2){
					 $re['res']='0';
				$re['mass']='B10';
				return $re; 
				}
		}
		//		花呗可用额度
		if($data5['alipaywealth']['huabei_creditamount']/100<$data['zhifubao_5']){
			if($data['zhifubao_5_status']==2){
					 $re['res']='0';
				$re['mass']='B11';
				return $re; 
				}
		}
//		淘宝收货地址

		if(count($data5['deliveraddress'])<1){
			if($data['zhifubao_6_status']==2){
					 $re['res']='0';
				$re['mass']='B12';
				return $re; 
				}
		}
//		运营商数据判断
//p($data6['basic_check_items']);
//p($data6);die;
		foreach ($data6['basic_check_items'] as $k => $v) {
			if($v['check_item']=='is_name_and_idcard_in_court_black'){
		//		申请人姓名+身份证号码是否出现在法院黑名单
				if($v['result']=='是'){
					if($data['yunying_1_status']==2){
						$re['res']='0';
						$re['mass']='C01';
						return $re; 
					}
				}
				
			}
			if($v['check_item']=='is_name_and_idcard_in_finance_black'){
		//		申请人姓名+身份证号码是否出现在金融机构黑名单
				if($v['result']=='是'){
					if($data['yunying_2_status']==2){
						 $re['res']='0';
						$re['mass']='C02';
						return $re; 
					}	
				}
			}
			if($v['check_item']=='is_name_and_mobile_in_finance_black'){
		//		申请人姓名+手机号码是否出现在金融机构黑名单
				if($v['result']=='是'){
					if($data['yunying_3_status']==2){
						 $re['res']='0';
						$re['mass']='C03';
						return $re; 
					}	
				}
			}
		}
		
		foreach ($data6['cell_phone'] as $k => $v) {
			if($v['key']=='reliability'){
		//实名认证
				if($v['value']!='实名认证'){
					if($data['yunying_4_status']==2){
						$re['res']='0';
						$re['mass']='C04';
						return $re; 
					}
				}
				
			}
		}
//		入网时长
		foreach ($data6['cell_phone'] as $k => $v) {
					if($v['key']=='in_time'){
				//实名认证
						if($v['value']<$data['yunying_5']){
						
							if($data['yunying_5_status']==2){
								$re['res']='0';
								$re['mass']='C05';
								
								return $re; 
							}
						}
				    }
		}
//年龄小于
		foreach ($data6['user_basic'] as $k => $v) {
					if($v['key']=='age'){
						if($v['value']<$data['yunying_6']){
//							p($data['yunying_6']);die;
							if($data['yunying_6_status']==2){
								$re['res']='0';
								$re['mass']='C06';
								return $re; 
							}
						}
						
					}
				}
		
		
//黑中介分
//p($data6['user_info_check']['0']['check_black_info']['phone_gray_score']);die;
//		if($data6['user_info_check']['0']['check_black_info']['phone_gray_score']<$data['yunying_7']){
//			if($data['yunying_7_status']==2){
//					    $re['res']='0';
//						$re['mass']='C07';
//						return $re; 
//			}
//		}
//		年龄大于
		foreach ($data6['user_basic'] as $k => $v) {
					if($v['key']=='age'){
		//			
						if($v['value']>$data['yunying_8']){
//							p($data['yunying_6']);die;
							if($data['yunying_8_status']==2){
								$re['res']='0';
								$re['mass']='C08';
								return $re; 
							}
						}
						
					}
				}

//通讯录个数
        if($num<$data['yunying_9']){
			if($data['yunying_9_status']==2){
//			p($data6['user_info_check']['0']['check_black_info']['phone_gray_score']);
//			p($data['yunying_7']);die;
					    $re['res']='0';
						$re['mass']='C09';
						return $re; 
			}
		}
		 
//p($data6['active_degree']);die;
//		3个月被叫次数小于、
foreach ($data6['active_degree'] as $k => $v) {
					if($v['app_point']=='dialed_cnt'){
						if($v['item']['item_3m']<$data['yunying_10']){
//							p($data['yunying_6']);die;
							if($data['yunying_10_status']==2){
								$re['res']='0';
								$re['mass']='C10';
								return $re; 
							}
						}
						
					}
				}



//有效联系人小于25拒贷
foreach ($data6['behavior_check'] as $k => $v) {
	if($v['check_point']=='contact_each_other'){
		$num=mb_substr($v['evidence'], 9,2,'utf-8');
		if($num<$data['yunying_11']){
			
////			p($data['yunying_11']);
//			p($num);die;
			if($data['yunying_11_status']==2){
								$re['res']='0';
								$re['mass']='C11';
								return $re; 
								
							}
		}
	}
}
//12*不重复通讯录人数<10人，
//p($data9);die;
if($data9<$data['yunying_12']){
////			p($data['yunying_11']);
//			p($num);die;
			if($data['yunying_12_status']==2){
								$re['res']='0';
								$re['mass']='C12';
								return $re; 
								
			}
		}


//p($data9);die;
//


//最近一次通话时间距今天数>30天拒贷 
//p($data8['calls']['0']['items']['0']['time']);die;
$timeend=$data8['calls']['0']['items']['0']['time'];
$timestar=time();
$time=$timestar-strtotime($timeend);
$days=$time/86400;
$days=substr($days,0,1);
//13*最近一次通话时间距今天数>30天拒贷
	if($days>$data['yunying_13']){
//							p($data['yunying_6']);die;
							if($data['yunying_13_status']==2){
								$re['res']='0';
								$re['mass']='C13';
								return $re; 
							}
						}
//p($data6['consumption_detail']);die;
//14*近6个月短信中出现“逾期、欠款“等字样>10条，则拒贷



//1:30-5:30   j三个月 通话次数   大于10
//三个月内通话记录中凌晨2:00～5:00通话记录超过十次
//p($data6['call_duration_detail']);die;
foreach ($data6['call_duration_detail'] as $k => $v) {
	if($v['key']=='call_duration_detail_3m'){
		foreach ($v['duration_list'] as $kk => $vv) {
			if($vv['time_step']=='midnight'){
				
//				p($vv['item']['total_cnt']);die;
				if($vv['item']['total_cnt']>$data['yunying_15']){
					          $re['res']='0';
								$re['mass']='C15';
								return $re; 
				}
				
			}
		}	
	}
}


//平均消费小于30
foreach ($data6['consumption_detail'] as $k => $v) {
					if($v['app_point']=='recharge_amount'){
						if($v['item']['avg_item_6m']<$data['yunying_16']){
//							p($data['yunying_6']);die;
							if($data['yunying_16_status']==2){
								$re['res']='0';
								$re['mass']='C16';
								return $re; 
							}
						}
						
					}
				}

//17*近3月通话催收公司出现次数大于3次     没有真实数据暂时无法获取
//p($data6['behavior_check']);die;
//$cuishou='';
//foreach ($data6['behavior_check'] as $key => $value) {
//	if($value['check_point']=='contact_collection'){
//		$cuishou=$value['evidence'];
//			$cuishou=mb_substr($cuishou,-2,1,'utf-8');
//			
//	}
//}
//	if($cuishou>$data['yunying_17']){
////							p($data['yunying_6']);die;
//							if($data['yunying_17_status']==2){
//								$re['res']='0';
//								$re['mass']='C17';
//								return $re; 
//							}
//						}
//	
	
//	t18淘宝宝近3个月虚拟交易金额比例大于40%拒贷
//查询淘宝报告数据接口
$xuniwupin=$data10['consumption_analysis']['special_consumption']['virtual_goods_rate']['sum'];
	if($xuniwupin>$data['yunying_18']){
////							p($data['yunying_6']);die;
							if($data['yunying_18_status']==2){
								$re['res']='0';
								$re['mass']='C18';
								return $re; 
							}
						}

//手机归属地是潍坊拒贷
if($data8['city']=='潍坊'){
	if($data['yunying_19_status']==2){
								$re['res']='0';
								$re['mass']='C19';
								return $re; 
							}
}

////13*3日内，同一ip地址的申请数量>5,则拒贷 
if($inxi['ip']>$data['ss_1012']){
	if($data['ss_1012_status']==2){
		$re['res']='0';
		$re['mass']='A13';
	    return $re; 
	}
}
//15*3日内，同一wifi名称的申请数>5,则拒贷 

if($inxi['wifi']>$data['ss_1014']){
	if($data['ss_1014_status']==2){
		$re['res']='0';
		$re['mass']='A15';
	    return $re; 
	}
}

	    $re['res']='1';
		$re['mass']='0000';
		return $re;
			   
	}
    /**
     * @功能说明: 订单列表
     * @传输格式: 私有token,有提交，密文返回
     * @提交网址: /center/Order/orderlist
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"page":"0","rows":"20","status":"6"}}
     *  status 订单状态 0申请中 1放款中 2已放款 3已完成 4已取消 5已拒绝 6全部
     * @返回信息: {'result'=>1,'message'=>'恭喜您，获取成功！','data'}
     */
    public function orderlist()
    {
        $para = get_json_data();
        $mem = getUserInfo(get_login_info('ID'));

        if (!in_array($para['status'], array('0', '1', '2', '3', '4', '5', '6'))) {
            AjaxJson(0, 0, '订单状态异常！');
        }
        $page = $para['page'] ? $para['page'] : 0;
        $rows = $para['rows'] ? $para['rows'] : 10;
        $statusArr = $this->statusArr;
        $where = array();
        $where['UserID'] = array('eq', $mem['ID']);
        $where['IsDel'] = array('eq', '0');
        if ($para['status'] != '6') {
            $where['LoanStatus'] = array('eq', $para['status']);
        }
        $orderlist = M('loans_applylist')->field('ID,ApplyTime,OrderSn,ApplyMoney,ApplyDay,LoanType,LoanStatus,OpenTime,YyFkTime,IsYQ')
            ->where($where)->order('ID desc')->limit($page * $rows, $rows)->select();
        if ($orderlist) {
            foreach ($orderlist as $k => &$v) {
                if ($v['LoanType'] == '0') {
                    $v['LoanType'] = '普通借款';
                } elseif ($v['LoanType'] == '1') {
                    $v['LoanType'] = '续借';
                } elseif ($v['LoanType'] == '2') {
                    $v['LoanType'] = '分期';
                }
                if (!$v['OpenTime']) {
                    $v['OpenTime'] = '';
                }
                if (!$v['YyFkTime']) {
                    $v['YyFkTime'] = '';
                }
                //查看是否逾期
                if ($v['LoanStatus'] == '2') {
                    //过了当天夜里24点才算逾期
                    $overtimes = '';
                    $overtimes = date('Y-m-d', strtotime($v['YyFkTime'])) . ' 23:59:59';
                    if ($overtimes < date('Y-m-d H:i:s')) {
                        // $yuqidata='';
                        // $yuqidata=getoverinfos($v['ID']);
                        // $retdata['TotalMoney']=$yuqidata['realtotal'];
                        // $retdata['famoney']=$yuqidata['famoney'];
                        $v['IsYQ'] = '1';
                    } else {
                        //未逾期
                        $v['IsYQ'] = '0';
                        //$retdata['TotalMoney']=$v['BackM'];
                    }
                }
                $v['statusname'] = $statusArr[$v['LoanStatus']];
            }
        }
        AjaxJson(1, 1, '恭喜您，数据查询成功！', $orderlist, 1, $mem['KEY'], $mem['IV']);
    }
    /**
     * @功能说明: 取消订单
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/cancelorder
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2","ordersn":"12352222"}}
     *   oid 订单的主键id   ordersn订单编号
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function cancelorder()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        $orderinfo = M(self::T_LOANSAPPLYLIST)->field('ID,Status')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'UserID' => $mem['ID'], 'IsDel' => '0'))->find();
        if (!$orderinfo) {
            AjaxJson(0, 0, '订单信息不存在！');
        }
        if ($orderinfo['Status'] != '0') {
            AjaxJson(0, 0, '此订单不能取消操作！');
        }
        $result = M(self::T_LOANSAPPLYLIST)->where(array('ID' => $para['oid']))->save(array('LoanStatus' => '4'));
        if ($result) {
            AjaxJson(0, 1, '取消成功！');
        } else {
            AjaxJson(0, 0, '取消失败！');
        }
    }
    /**
     * @功能说明: 借款合同
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/hetong
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2","ordersn":"12352222"}}
     *   oid 订单的主键id   ordersn订单编号
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function hetong()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        $orderinfo = M(self::T_LOANSAPPLYLIST)->field('ID,OrderSn,ApplyTime,ApplyMoney,ApplyDay,OpenTime,Interest,FJMoney,AdoptMoney,YyFkTime,BackM')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'UserID' => $mem['ID'], 'LoanStatus' => array('in', array('2', '3')), 'IsDel' => '0'))->find();
        if (!$orderinfo) {
            AjaxJson(0, 0, '订单信息不存在！');
        }
        $meminfo = M(self::T_MEMINFO)->field('Mobile,TrueName,IDCard')->find($mem['ID']);
        $hetonginfo = M(self::T_CONTENTMANAGEMENT)->field('Contents')->where(array('CategoriesID' => '18'))->find();
        $hetonginfo['Contents'] = htmlspecialchars_decode($hetonginfo['Contents']);
        //替换操作
        $hetonginfo['Contents'] = str_replace('{$ContractNO}', $orderinfo['OrderSn'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$AddTime}', $orderinfo['OpenTime'], $hetonginfo['Contents']);

        $hetonginfo['Contents'] = str_replace('{$Lender}', get_basic_info('CompanyName'), $hetonginfo['Contents']);

        $hetonginfo['Contents'] = str_replace('{$Borrower}', $meminfo['TrueName'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$BIdenty}', $meminfo['IDCard'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$BMobile}', $meminfo['Mobile'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$loanTime}', date('Y-m-d', strtotime($orderinfo['ApplyTime'])), $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$Principal}', $orderinfo['ApplyMoney'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$term}', $orderinfo['ApplyDay'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$Interest}', $orderinfo['Interest'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$Userfee}', $orderinfo['FJMoney'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$Applyfee}', $orderinfo['AdoptMoney'], $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$repayTime}', date('Y-m-d', strtotime($orderinfo['YyFkTime'])), $hetonginfo['Contents']);
        $hetonginfo['Contents'] = str_replace('{$repayMoney}', $orderinfo['BackM'], $hetonginfo['Contents']);
        AjaxJson(0, 1, '恭喜您，数据查询成功！', $hetonginfo, 1, $mem['KEY'], $mem['IV']);
    }
    /**
     * @功能说明: 获取订单简单信息(我要还款页面)
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/hhdetails
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2","ordersn":"12352222"}}
     *   oid 订单的主键id   ordersn订单编号
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function hhdetails()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        $orderinfo = M(self::T_LOANSAPPLYLIST)->field('ID,LoanStatus,ApplyTime,YyFkTime,OrderSn,ApplyMoney,AdoptMoney,FJMoney,Interest,BackM,CoMoney')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'UserID' => $mem['ID'], 'IsDel' => '0'))->find();
        if (!$orderinfo) {
            AjaxJson(0, 0, '订单信息不存在！');
        }
        if ($orderinfo['LoanStatus'] != '2') {
            AjaxJson(0, 0, '此订单不能进行此操作了！');
        }
        $statusArr = $this->statusArr;

        $retdata = array();//返回的详情信息
        $retdata['isjump'] = '1';//能跳
        $retdata['errmsg'] = '';
        $retdata['Status'] = $orderinfo['LoanStatus'];
        $retdata['Statusname'] = $statusArr[$orderinfo['LoanStatus']];
        $retdata['ApplyTime'] = $orderinfo['ApplyTime'];
        $retdata['YyFkTime'] = $orderinfo['YyFkTime'];
        $retdata['OrderSn'] = $orderinfo['OrderSn'];
        $retdata['ApplyMoney'] = $orderinfo['ApplyMoney'];
        $retdata['AdoptMoney'] = $orderinfo['AdoptMoney'];
        $retdata['FJMoney'] = $orderinfo['FJMoney'];
        $retdata['Interest'] = $orderinfo['Interest'];
        $retdata['CoMoney'] = '';
        if ($orderinfo['CoMoney']) {
            $retdata['CoMoney'] = $orderinfo['CoMoney'];
        }
        $retdata['famoney'] = '';
               
        //查看是否逾期
        //过了当天夜里24点才算逾期
        $overtimes = date('Y-m-d', strtotime($orderinfo['YyFkTime'])) . ' 23:59:59';
        if ($overtimes < date('Y-m-d H:i:s')) {
            $yuqidata = '';
            $yuqidata = getoverinfos($orderinfo['ID']);
            $retdata['TotalMoney'] = $yuqidata['realtotal'];
            $retdata['famoney'] = $yuqidata['famoney'];
            $retdata['IsYQ'] = '1';
            
            //算出距离发货日
            $lastday = (strtotime($overtimes) - time()) / 86400;
            $lastday = abs($lastday);
            $lastday = ceil($lastday);
            $retdata['lastday'] = -$lastday;
            //算出总天数
            $totaldays = '0';
            $totaldays = (strtotime($overtimes) - strtotime($orderinfo['ApplyTime'])) / 86400;
            $totaldays = ceil($totaldays);
            $retdata['totaldays'] = $totaldays;
        } else {
            //未逾期
            $retdata['IsYQ'] = '0';
            $retdata['TotalMoney'] = $orderinfo['BackM'];

            //算出距离发货日
            $lastday = (strtotime($orderinfo['YyFkTime']) - time()) / 86400;
            $lastday = ceil($lastday);
            $retdata['lastday'] = $lastday;
            //算出总天数
            $totaldays = '0';
            $totaldays = (strtotime($orderinfo['YyFkTime']) - strtotime($orderinfo['ApplyTime'])) / 86400;
            $totaldays = ceil($totaldays);
            $retdata['totaldays'] = $totaldays;
        }
        //校验是否提交借款申请，或是提交了续借申请了
        //如果还款申请已经提交，并且还处于待审核状态，则不予提交
        $checkresult = M('loans_hklist')->where(array('ApplyID' => $orderinfo['ID'], 'PayStatus' => '0', 'Status' => '0', 'PayType' => array('neq', '3')))->count('ID');
        if ($checkresult) {
            $retdata['isjump'] = '0';//不能跳
            $retdata['errmsg'] = '还款申请审核中!';
        }
        //如果续借还在审核 不予提交
        $checkxj = M('loans_xjapplylist')->where(array('ApplyID' => $orderinfo['ID'], 'PayStatus' => '0', 'Status' => '0', 'PayType' => array('neq', '3')))->count('ID');
        if ($checkxj) {
            $retdata['isjump'] = '0';//不能跳
            $retdata['errmsg'] = '续借申请审核中!';
        }
        AjaxJson(0, 1, '恭喜您，数据查询成功！', $retdata, 1, $mem['KEY'], $mem['IV']);
    }
    /**
     * @功能说明: 订单详情页
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/orderdetails
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2","ordersn":"12352222"}}
     *   oid 订单的主键id   ordersn订单编号
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function orderdetails()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        $orderinfo = M(self::T_LOANSAPPLYLIST)->field('ID,LoanStatus,ApplyTime,YyFkTime,OrderSn,ApplyMoney,AdoptMoney,FJMoney,Interest,ApplyDay,LoanType,OpenTime,CoMoney')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'UserID' => $mem['ID'], 'IsDel' => '0'))->find();
        if (!$orderinfo) {
            AjaxJson(0, 0, '订单信息不存在！');
        }
        $statusArr = $this->statusArr;

        $retdata = array();//返回的详情信息
        $retdata['Status'] = $orderinfo['LoanStatus'];
        $retdata['Statusname'] = $statusArr[$orderinfo['LoanStatus']];
        $retdata['ApplyTime'] = $orderinfo['ApplyTime'];
        $retdata['YyFkTime'] = $orderinfo['YyFkTime'];
        $retdata['OrderSn'] = $orderinfo['OrderSn'];
        $retdata['ApplyMoney'] = $orderinfo['ApplyMoney'];
        $retdata['AdoptMoney'] = $orderinfo['AdoptMoney'];
        $retdata['FJMoney'] = $orderinfo['FJMoney'];
        $retdata['Interest'] = $orderinfo['Interest'];
        $retdata['ApplyDay'] = $orderinfo['ApplyDay'];
        $retdata['HkTime'] = '';

        if ($orderinfo['LoanType'] == '0') {
            $retdata['LoanType'] = '普通借款';
        } elseif ($orderinfo['LoanType'] == '1') {
            $retdata['LoanType'] = '续借';
        } elseif ($orderinfo['LoanType'] == '2') {
            $retdata['LoanType'] = '分期';
        }
        $retdata['OpenTime'] = '';
        if ($orderinfo['OpenTime']) {
            $retdata['OpenTime'] = $orderinfo['OpenTime'];
        }
        $retdata['CoMoney'] = '';
        if ($orderinfo['CoMoney']) {
            $retdata['CoMoney'] = $orderinfo['CoMoney'];
        }
        //未逾期
        $retdata['overdays'] = '0';
        $retdata['overmoney'] = '0.00';
        //算出逾期金额和逾期天数
        if (in_array($orderinfo['LoanStatus'], array('0', '1', '4', '5'))) {
            $retdata['overdays'] = '0';
            $retdata['overmoney'] = '0.00';
        } elseif ($orderinfo['LoanStatus'] == '2') {
            //查看是否逾期
            //过了当天夜里24点才算逾期
            $overtimes = date('Y-m-d', strtotime($orderinfo['YyFkTime'])) . ' 23:59:59';
            if ($overtimes < date('Y-m-d H:i:s')) {
                //已经逾期了
                $yuqidata = '';
                $yuqidata = getoverinfos($orderinfo['ID']);
                $retdata['overdays'] = $yuqidata['overdays'];
                $retdata['overmoney'] = $yuqidata['famoney'];
            } else {
                //未逾期
                $retdata['overdays'] = '0';
                $retdata['overmoney'] = '0.00';
            }
        } elseif ($orderinfo['LoanStatus'] == '3') {
            //已完成  查询还款记录
            $hkinfos = M(self::T_LOANSHKLIST)->field('ID,FinePayable,HkTime')->where(array('ApplyID' => $orderinfo['ID'], 'IsDel' => '0'))->find();
            if ($hkinfos) {
                $retdata['HkTime'] = $hkinfos['HkTime'];
                if ($hkinfos['FinePayable'] > 0) {
                    //表示逾期了
                    //过了当天夜里24点才算逾期
                    $overtimes = date('Y-m-d', strtotime($orderinfo['YyFkTime'])) . ' 23:59:59';

                    $overdays = strtotime($hkinfos['HkTime']) - strtotime($overtimes);
                    $overdays = $overdays / 86400;
                    $overdays = ceil($overdays);
                    $retdata['overdays'] = $overdays;
                    $retdata['overmoney'] = $hkinfos['FinePayable'];
                }
            } else {
                //如果不存在，则是续借的
                $xjtimes = M('loans_xjapplylist')->where(array('ApplyID' => $orderinfo['ID'], 'Status' => '1', 'PayStatus' => '1'))->getField('XjTime');
                $retdata['HkTime'] = $xjtimes;
            }
        }
        AjaxJson(0, 1, '恭喜您，数据查询成功！', $retdata, 1, $mem['KEY'], $mem['IV']);
    }
    /**
     * @功能说明: 还款支付方式
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/hkpaystype
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"0"}
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function hkpaystype()
    {
        $mem = getUserInfo(get_login_info('ID'));
        $retdata = array(
//          array('paytype'=>'1','name'=>'支付宝'),
//          array('paytype'=>'2','name'=>'微信'),
            array('paytype' => '3', 'name' => '银联'),
        );
        AjaxJson(1, 1, '恭喜您，数据查询成功！', $retdata, 1, $mem['KEY'], $mem['IV']);
    }
	
	//	协议卡解绑接口   获取协议号码

    public function xiyihaoma()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        $merchant = M('sys_inteparameter')->where(['ParaName' => 'mchntCd'])->getField('ParaValue');//商户号
        $key = M('sys_inteparameter')->where(['ParaName' => 'key'])->getField('ParaValue');//商户秘钥	  
        $user_id = $mem['ID'];//用户id
		$user_id ='8';//用户id 手动输入
        $Fuyou = new \Fuyou\Fuiou;
        $data = $Fuyou->xiyihaoma($merchant, $key, $user_id);
        if ($data['status'] == 1) {//银行卡解绑成功       
            AjaxJson(0, 1, $data['data']);
            die;
        } else {
            AjaxJson(0, 0, $data['data']);
            die;
        }
    }
//	协议卡解绑接口

    public function jiebang()
    {
        $para = get_json_data();//接收参数
        $merchant = M('sys_inteparameter')->where(['ParaName' => 'mchntCd'])->getField('ParaValue');//商户号
        $key = M('sys_inteparameter')->where(['ParaName' => 'key'])->getField('ParaValue');//商户秘钥	  
        $user_id = $para['UserID'];//用户id
        $protolno = M('renzen_bank')->where(['UserID' => $user_id])->getField(['PROTOCOLNO']);//首次协议交易成功好生成的协议号
        $Fuyou = new \Fuyou\Fuiou;
        $data = $Fuyou->jiebang($merchant, $key, $user_id, $protolno);
        if ($data['status'] == 1) {//银行卡解绑成功       
            AjaxJson(0, 1, $data['msg']);
            die;
        } else {
            AjaxJson(0, 0, $data['msg']);
            die;
        }
    }
	
	
	
    /**
     * @功能说明: 还款支付操作
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/hkpay
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2","ordersn":"12352222","paytype":"1","traderemark":"我用支付宝182@qq.com账号支付了100元"}}
     *   oid 订单的主键id   ordersn订单编号 paytype 还款类型 1支付宝 2微信 3银联 4代付
     *   traderemark 转账备注信息
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function hkpay()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        if (!in_array($para['paytype'], array('1', '2', '3'))) {
            AjaxJson(0, 0, '还款类型不正确！');
        }
        if ($para['paytype'] != '3' && !$para['traderemark']) {
            AjaxJson(0, 0, '转账备注信息必须提交！');
        }
        $BankNo = '';
        if ($para['paytype'] == '3') {
            //银联还款  查询自己的认证银行卡号
            $baninfos = M('renzen_bank')->field('ID,BankNo')->where(array('UserID' => $mem['ID'], 'Status' => '1', 'IsDel' => '0'))->find();
//			p($baninfos);
            if (!$baninfos) {
                AjaxJson(0, 0, '银行认证信息异常！');
            }
            $BankNo = $baninfos['BankNo'];
        }
        $applyinfo = M('loans_applylist')->field('ID,LoanNo,YyFkTime,BackM,ApplyMoney,AdoptMoney,FJMoney,Interest,CoMoney,UserID,OrderSn')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'LoanStatus' => '2', 'IsDel' => '0'))->find();
        if (!$applyinfo) {
            AjaxJson(0, 0, '借款订单不存在！');
        }
        //如果还款申请已经提交，并且还处于待审核状态，则不予提交
        $checkresult = M('loans_hklist')->field('ID,PayType')->where(array('ApplyID' => $applyinfo['ID'], 'PayStatus' => '0', 'Status' => '0'))->find();
        if ($checkresult) {
            if ($checkresult['PayType'] == '3') {//因为银联支付可以自动获取结果
                //银联支付   把此记录改成审核失败
                $sdata = array(
                    'ShTime' => date('Y-m-d H:i:s'),
                    'Status' => '2',
                );
                M('loans_hklist')->where(array('ID' => $checkresult['ID']))->save($sdata);
            } else {
                AjaxJson(0, 0, '您已经提交支付申请，并在审核中！');
            }
        }
        //如果续借还在审核 不予提交
        $checkxj = M('loans_xjapplylist')->field('ID,PayType')->where(array('ApplyID' => $applyinfo['ID'], 'PayStatus' => '0', 'Status' => '0'))->find();
        if ($checkxj) {
            if ($checkxj['PayType'] == '3') {
                //银联支付   把此记录改成审核失败
                $sdata = array(
                    'ShTime' => date('Y-m-d H:i:s'),
                    'Status' => '2',
                );
                M('loans_xjapplylist')->where(array('ID' => $checkxj['ID']))->save($sdata);
            } else {
                AjaxJson(0, 0, '您提交的续借申请还在审核中！');
            }
        }
        //还款操作
        $hkdata = array(
            'UserID' => $mem['ID'],
            'ApplyID' => $applyinfo['ID'],
            'OrderSn' => date(ymd) . rand(1, 9) . date(His) . rand(111, 999),
            'LoanNo' => $applyinfo['LoanNo'],
            'HkTime' => date('Y-m-d H:i:s'),
        );
        //过了当天夜里24点才算逾期
        $overtimes = date('Y-m-d', strtotime($applyinfo['YyFkTime'])) . ' 23:59:59';
        if ($overtimes < date('Y-m-d H:i:s')) {
            //已经逾期了
            $yuqidata = getoverinfos($applyinfo['ID']);
            $hkdata['TotalMoney'] = $yuqidata['realtotal'];//应付总金额
            $hkdata['FinePayable'] = $yuqidata['famoney'];//应还罚金
        } else {
            //未逾期
            $hkdata['TotalMoney'] = $applyinfo['BackM'];//到期应还
        }
        $hkdata['CostPayable'] = $applyinfo['ApplyMoney'] - $applyinfo['CoMoney'];//应还本金
        //$hkdata['SeviceCostPayable']=$applyinfo['FJMoney'];//应还服务费
        $hkdata['RatePayable'] = $applyinfo['Interest'];//应还本息
        if ($para['paytype'] != '3') {
            $hkdata['TradeRemark'] = $para['traderemark'];
            if ($para['paytype'] == '1') {
                $hkdata['Accounts'] = get_basic_info('Gfaccount');//1支付宝 
            } elseif ($para['paytype'] == '2') {
                $hkdata['Accounts'] = get_basic_info('Gfaccountw');//2微信
            }
        }
        $hkdata['PayType'] = $para['paytype'];
        $result = M('loans_hklist')->add($hkdata);//创建还款订单
        if ($result) {
            if ($para['paytype'] == 3) {
                $TotalMoney = M('loans_hklist')->where(['ID' => $result])->getField('TotalMoney');//获取需要还款的额度			
                $merchant = M('sys_inteparameter')->where(['ParaName' => 'mchntCd'])->getField('ParaValue');//商户号
                $key = M('sys_inteparameter')->where(['ParaName' => 'key'])->getField('ParaValue');//商户秘钥	  
                $user_id = $mem['ID'];//用户id
                $order_no = $applyinfo['LoanNo'];//订单号
                $user_ip = '47.93.55.128';//用户ip
                $amt = $TotalMoney * 100;//金额
                if($user_id=='3'){
                	
				  $amt=1;//测试金额一块钱
                }
                
                
                $protolno = M('renzen_bank')->where(['UserID' => $mem['ID']])->getField(['PROTOCOLNO']);//首次协议交易成功好生成的协议号
                $back_url = "http://" . $_SERVER['HTTP_HOST'] . '/api.php/Center/Notify/hkquery';//支付结果回调地址  并没有很么卵用  没有处理回调信息
		        //调用富有协议支付
                $Fuyou = new \Fuyou\Fuiou;
                $data = $Fuyou->newpropay_order($merchant, $key, $user_id, $order_no, $user_ip, $amt, $protolno, $back_url);
//				将返回的数据写入文件
                $requestBody=json_encode($data,JSON_UNESCAPED_UNICODE);
				$myfile = fopen("还款返回结果.txt", "a+") or die("Unable to open file!");
				fwrite($myfile,date('Y-m-d h:i:s',time()));
				fwrite($myfile,$requestBody);
				fclose($myfile);
                if ($data['status'] == 1) {//银行卡还款成功
			        //开启事物操作
//                  $model = M();
//                  $model->startTrans();
//                  
                    //修改会员状态为老用户
                    $result1 = M('mem_info')->where(['ID' => $applyinfo['UserID']])->save(['IsNewUser' => 2]);
					
					//修改订单为已完成
                    $reS = M('loans_applylist')->where(['ID' => $para['oid']])->save(['LoanStatus' => '3']);//更改订单状态  为已经完成

                    //修改还款记录
                    $status['PayStatus'] = '1'; //支付状态 0待支付 1已支付
                    $status['Status'] = '1';    //审核状态 0待审核 1审核成功 2审核失败
                    $status['ShTime'] = date('Y-m-d H:i:s'); //还款时间
                    $status['tijiaopay'] = '1';
                    $status['AdminID'] = '2';   //审核员编号
                    $status['msg'] =$data['msg'];
                    $status['ORDERID']=$data['data']['ORDERID'];//富友订单号
                    $reV = M('loans_hklist')->where(['ID' => $result])->save($status);//更改还款订单状态为已经还款

                    //创建支付记录
                    $tempData = [
                        'UserID'  => $applyinfo['UserID'],    //用户ID
                        'OrderSn' => $applyinfo['OrderSn'],   //订单单号
                        'LoanNo'  => $applyinfo['LoanNo'],    //申请号
                        'PayType' => 3,      //付款方式  未付款 1支付宝 2微信 3银联 4代付 5线下还款
                        'TradeType'   => 2,  //付款类型 1续借 2线上还款 3放款 4购买商品 5线下还款
                        'PayStatus'   => 1,  //支付状态 0待支付 1已支付
                        'OrderAmount' => (int)($amt/100),//还款金额
//                        'OperatorID'  => session('AdminInfo.AdminID'),  //操作者ID
                        'UpdateTime'  => date('Y-m-d H:i:s',time()),      //生成时间
                        'Description' => '用户APP还款',                    //描述
//                        'CollectionAccount' => $_POST['RepaymentAccount'],//收款账户
                    ];
                    $result3 = M('loans_paylist')->add($tempData);

                    //发送成功还款短信通知
                    $where['EName'] = 'repayment_Inform';
                    $where['Status'] = 1;
                    $msgTemplate = M('sys_smstemplates')->where($where)->find();
                    if (!empty($msgTemplate) && isset($msgTemplate['Content'])) {
                        //获取用户真实姓名发送短信使用
                        $userInfo = M('mem_info')->where(array('ID' => $applyinfo['UserID']))->find();
                        if (!empty($userInfo['TrueName']) && isset($userInfo['TrueName'])) {
                            $arr1 = ['#name#', '#money#'];
                            $arr2 = [$userInfo['TrueName'], $hkdata['TotalMoney']];
                            $msgTemplate['Content'] = str_replace($arr1, $arr2, $msgTemplate['Content']);
                            //发送短信
                            $msgObj = new MessageController();
                            $msgObj->send_msg($userInfo['Mobile'], $msgTemplate['Content']);
                        }
                    }

                    if ($reV && $reS && $result3 && $result1) {
//                      $model->commit();//事物提交
			            //还款成功返回状态
                        AjaxJson(0, 1, $data['msg']);
                        die;
                    } else {
//                      $model->rollback();//事物回滚
			            //还款失败返回状态
                        AjaxJson(0, 1, $data['msg']);
                        die;
                    }
                } else {
                    $status['ShTime'] = date('Y-m-d H:i:s');
                    $status['PayStatus'] = '0';
                    $status['Status'] = '2';
                    $status['tijiaopay'] = '1';
                    $status['AdminID'] = '2';
					$status['msg'] =$data['msg'];
					$status['ORDERID']=$data['data']['ORDERID'];//富友订单号
                    $reV = M('loans_hklist')->where(['ID' => $result])->save($status);//更改还款订单状态为失败
                    if ($reV) {
                        AjaxJson(0, 0, $data['msg']);
                        die;
                    }
                }
            } else {
                AjaxJson(0, 1, '还款记录提交成功，等待审核！', $retdata);//还款记录提交成功
            }
        } else {
            AjaxJson(0, 0, '还款记录提交失败！');
        }
    }
    /**
     * @功能说明: 获取续借信息(续借选择页-我要续借页面)
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/xjdetails
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2","ordersn":"12352222"}}
     *   oid 订单的主键id ordersn订单编号
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function xjdetails()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        $applyinfo = M('loans_applylist')->field('ID,LoanNo,YyFkTime,ProductID')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'UserID' => $mem['ID'], 'LoanStatus' => '2', 'IsDel' => '0'))->find();
        if (!$applyinfo) {
            AjaxJson(0, 0, '借款订单不存在！');
        }
        //过了当天夜里24点才算逾期
        $overtimes = date('Y-m-d', strtotime($applyinfo['YyFkTime'])) . ' 23:59:59';
        if ($overtimes < date('Y-m-d H:i:s')) {
            AjaxJson(0, 0, '此单已经逾期，不能续借！');
        }
        //判断第几次续借了
        $xjnumbs = M('loans_applylist')->where(array('LoanNo' => $applyinfo['LoanNo'], 'LoanType' => '1', 'IsDel' => '0'))->count('ID');
        if (!$xjnumbs) {
            $xjnumbs = '0';
        }

        $loansets = M('loans_parameter')->find();
        if ($loansets['MaxRenewSum'] <= $xjnumbs) {
            AjaxJson(0, 0, '此单已经续借多次，不能再续借了！');
        }
        //获取借款期限
        $termlist = M('loans_term')->field('ID,NumDays,ServiceCost')->where(array('Status' => '1', 'IsDel' => '0'))->order('Sort asc,ID desc')->select();
        //获取 快速申请费
        $fast_Applyfee = '0';
        $maxfee = '';
        $currentfee = '';
        //续借参数设置
        $renewsetlist = M('loans_renewset')->field('Nums,Applyfee')->where(array('Status' => '1', 'IsDel' => '0'))->order('Nums asc')->select();
        foreach ($renewsetlist as $k => $v) {
            if ($v['Nums'] == ($xjnumbs + 1)) {
                $currentfee = $v['Applyfee'];
            }
            $maxfee = $v['Applyfee'];
        }
        if ($currentfee) {
            $fast_Applyfee = $currentfee;
        } else {
            $fast_Applyfee = $maxfee;
        }
        //商品续借费
        $goodinfo = M('goods')->field('ServiceCost')->where(array('ID' => $applyinfo['ProductID'], 'IsShelves' => '1', 'IsDel' => '0'))->find();
        if (!$goodinfo) {
            AjaxJson(0, 0, '商品信息异常，暂不能续借！');
        }
        $retdata = array(
            'arrivetime' => $overtimes,
            'termlist' => $termlist,
            'xjfee' => $fast_Applyfee + $goodinfo['ServiceCost'],
        );
        AjaxJson(1, 1, '恭喜您，数据查询成功！', $retdata, 1, $mem['KEY'], $mem['IV']);
    }
    /**
     * @功能说明: 获取续借支付总金额
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/getxjfee
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2","ordersn":"12352222","termid":"1"}}
     *   oid 订单的主键id  ordersn订单编号  termid续借期限id
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function getxjfee()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        $applyinfo = M('loans_applylist')->field('ID,LoanNo,ProductID')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'UserID' => $mem['ID'], 'LoanStatus' => '2', 'IsDel' => '0'))->find();
        if (!$applyinfo) {
            AjaxJson(0, 0, '借款订单不存在！');
        }
        //判断第几次续借了
        $xjnumbs = M('loans_applylist')->where(array('LoanNo' => $applyinfo['LoanNo'], 'LoanType' => '1', 'IsDel' => '0'))->count('ID');
        if (!$xjnumbs) {
            $xjnumbs = '0';
        }
        //获取借款期限
        $terminfo = M('loans_term')->field('ID,NumDays,ServiceCost')->where(array('ID' => $para['termid'], 'Status' => '1', 'IsDel' => '0'))->find();
        if (!$terminfo) {
            AjaxJson(0, 0, '借款期限异常！');
        }
        //获取 快速申请费
        $fast_Applyfee = '0';
        $maxfee = '';
        $currentfee = '';
        //续借参数设置
        $renewsetlist = M('loans_renewset')->field('Nums,Applyfee')->where(array('Status' => '1', 'IsDel' => '0'))->order('Nums asc')->select();
        foreach ($renewsetlist as $k => $v) {
            if ($v['Nums'] == ($xjnumbs + 1)) {
                $currentfee = $v['Applyfee'];
            }
            $maxfee = $v['Applyfee'];
        }
        if ($currentfee) {
            $fast_Applyfee = $currentfee;
        } else {
            $fast_Applyfee = $maxfee;
        }
        //商品续借费
        $goodinfo = M('goods')->field('ServiceCost')->where(array('ID' => $applyinfo['ProductID'], 'IsShelves' => '1', 'IsDel' => '0'))->find();
        if (!$goodinfo) {
            AjaxJson(0, 0, '商品信息异常，暂不能续借！');
        }
        $retdata = array(
            'xjtotalmoney' => $fast_Applyfee + $terminfo['ServiceCost'] + $goodinfo['ServiceCost'],
        );
        AjaxJson(0, 1, '恭喜您，数据查询成功！', $retdata, 1, $mem['KEY'], $mem['IV']);
    }
    /**
     * @功能说明: 续借支付确认操作(选择支付方式页面)
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/xjpay
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2",,"ordersn":"12352222""termid":"1","paytype":"1","traderemark":"我用支付宝182@qq.com账号支付了100元"}}
     *   oid 订单的主键id  ordersn订单编号  termid续借期限id paytype 支付类型 1支付宝 2微信 3银联 4代付
     *   traderemark 转账备注信息
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function xjpay()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
//		p($para);die;
//		p($mem);die;
        //校验
        if (!in_array($para['paytype'], array('1', '2', '3', '4'))) {
            AjaxJson(0, 0, '还款类型不正确！');
        }
        if ($para['paytype'] != '3' && !$para['traderemark']) {
            AjaxJson(0, 0, '转账备注信息必须提交！');
        }
        $BankNo = '';
        if ($para['paytype'] == '3') {
            //银联还款  查询自己的认证银行卡号
            $baninfos = M('renzen_bank')->field('ID,BankNo')->where(array('UserID' => $mem['ID'], 'Status' => '1', 'IsDel' => '0'))->find();
            if (!$baninfos) {
                AjaxJson(0, 0, '银行认证信息异常！');
            }
            $BankNo = $baninfos['BankNo'];
        }

        $applyinfo = M('loans_applylist')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'UserID' => $mem['ID'], 'LoanStatus' => '2', 'IsDel' => '0'))->find();
        if (!$applyinfo) {
            AjaxJson(0, 0, '借款订单不存在！');
        }
        //过了当天夜里24点才算逾期
        $overtimes = date('Y-m-d', strtotime($applyinfo['YyFkTime'])) . ' 23:59:59';
        if ($overtimes < date('Y-m-d H:i:s')) {
            AjaxJson(0, 0, '此单已经逾期，不能续借！');
        }
        //如果还款还在审核 不予提交
        $checkhks = M('loans_hklist')->field('ID,PayType')->where(array('ApplyID' => $applyinfo['ID'], 'PayStatus' => '0', 'Status' => '0'))->find();
        if ($checkhks) {
            if ($checkhks['PayType'] == '3') {
                //银联支付   把此记录改成审核失败
                $sdata = array(
                    'ShTime' => date('Y-m-d H:i:s'),
                    'Status' => '2',
                );
                M('loans_hklist')->where(array('ID' => $checkhks['ID']))->save($sdata);
            } else {
                AjaxJson(0, 0, '您提交的还款申请还在审核中！');
            }
        }
        
        //判断第几次续借了
        $xjnumbs = M('loans_applylist')->where(array('LoanNo' => $applyinfo['LoanNo'], 'LoanType' => '1', 'IsDel' => '0'))->count('ID');
        if (!$xjnumbs) {
            $xjnumbs = '0';
        }
        $loansets = M('loans_parameter')->find();
        if ($loansets['MaxRenewSum'] <= $xjnumbs) {
            AjaxJson(0, 0, '此单已经续借多次，不能再续借了！');
        }
        //获取借款期限
        $terminfo = M('loans_term')->field('ID,NumDays,ServiceCost')->where(array('ID' => $para['termid'], 'Status' => '1', 'IsDel' => '0'))->find();
        if (!$terminfo) {
            AjaxJson(0, 0, '借款期限异常！');
        }
        //获取 快速申请费
        $fast_Applyfee = '0';
        $maxfee = '';
        $currentfee = '';
        //续借参数设置
        $renewsetlist = M('loans_renewset')->field('Nums,Applyfee')->where(array('Status' => '1', 'IsDel' => '0'))->order('Nums asc')->select();
        foreach ($renewsetlist as $k => $v) {
            if ($v['Nums'] == ($xjnumbs + 1)) {
                $currentfee = $v['Applyfee'];
            }
            $maxfee = $v['Applyfee'];
        }
        if ($currentfee) {
            $fast_Applyfee = $currentfee;
        } else {
            $fast_Applyfee = $maxfee;
        }
        //商品续借费
        $goodinfo = M('goods')->field('ServiceCost')->where(array('ID' => $applyinfo['ProductID'], 'IsShelves' => '1', 'IsDel' => '0'))->find();
        if (!$goodinfo) {
            AjaxJson(0, 0, '商品信息异常，暂不能续借！');
        }

        //如果续借申请已经提交，并且还处于待审核状态，则不予提交
        $checkresult = M('loans_xjapplylist')->field('ID,PayType')->where(array('ApplyID' => $applyinfo['ID'], 'PayStatus' => '0', 'Status' => '0'))->find();
        if ($checkresult) {
            if ($checkresult['PayType'] == '3') {
                //银联支付   把此记录改成审核失败
                $sdata = array(
                    'ShTime' => date('Y-m-d H:i:s'),
                    'Status' => '2',
                );
                M('loans_xjapplylist')->where(array('ID' => $checkresult['ID']))->save($sdata);
            } else {
                AjaxJson(0, 0, '您已经提交续借申请，并在审核中！');
            }
        }
        //续借操作
        $xjdata = array(
            'UserID' => $mem['ID'],
            'ApplyID' => $applyinfo['ID'],
            'OrderSn' => date(ymd) . rand(1, 9) . date(His) . rand(111, 999),
            'LoanNo' => $applyinfo['LoanNo'],
            'LoanDay' => $terminfo['NumDays'],
            'TotalMoney' => $fast_Applyfee + $terminfo['ServiceCost'] + $goodinfo['ServiceCost'],
            'ServiceCost' => $fast_Applyfee + $terminfo['ServiceCost'] + $goodinfo['ServiceCost'],
            'XjTime' => date('Y-m-d H:i:s'),//续借时间
            'PayTime' => date('Y-m-d H:i:s'),//支付时间
            'PayType' => $para['paytype'],
              'ShTime' => date('Y-m-d H:i:s'),//审核时间
        );
        if ($para['paytype'] != '3') {
            $xjdata['TradeRemark'] = $para['traderemark'];
            if ($para['paytype'] == '1') {
                $xjdata['Accounts'] = get_basic_info('Gfaccount');//1支付宝 
            } elseif ($para['paytype'] == '2') {
                $xjdata['Accounts'] = get_basic_info('Gfaccountw');//2微信
            }
        }
        $result = M('loans_xjapplylist')->add($xjdata);
        if ($result) {//银联操作
            if ($para['paytype'] == '3') {
//      		echo '银联';die;
 //				富有支付		
                $merchant = M('sys_inteparameter')->where(['ParaName' => 'mchntCd'])->getField('ParaValue');//商户号
                $key = M('sys_inteparameter')->where(['ParaName' => 'key'])->getField('ParaValue');//商户秘钥	  
                $user_id = $mem['ID'];//用户id
                $order_no = $xjdata['OrderSn'];//订单号
                $user_ip = '47.93.55.128';//用户ip
                $amt = $xjdata['TotalMoney'] * 100;//金额
                
                if($user_id=='3'){
//              	测试账户金额设置为一分
				  $amt=1;//测试金额一分钱
                }
//				$amt=100000000;//金额
                $protolno = M('renzen_bank')->where(['UserID' => $mem['ID']])->getField(['PROTOCOLNO']);//首次协议交易成功好生成的协议号
//				$protolno='3QQGN2100011496056YJUG';
                $back_url = "http://" . $_SERVER['HTTP_HOST'] . '/index.php/Fuyoupay/hkquery';//支付结果回调地址  并没有很么卵用  没有处理回调信息
//		        p($user_id);die;
		//      调用富有协议支付
                $Fuyou = new \Fuyou\Fuiou;
                $data = $Fuyou->newpropay_order($merchant, $key, $user_id, $order_no, $user_ip, $amt, $protolno, $back_url);
//				p($data);die;
                if ($data['status'] == 1) {//银行卡成功
                    //开启事物操作
//                  $model = M();
//                  $model->startTrans();
                    //更改订单表时间 加七天
                    $time1 = strtotime($applyinfo['YyFkTime']);
                    $time2 = 60 * 60 * 24 * 6;
                    $time = $time1 + $time2;
                    $days['YyFkTime'] = date('Y-m-d h:i:s', $time);
					
//					获取续交次数
					$xjnums = M('loans_applylist')->where(array('ID' => $para['oid'], 'LoanNo' => $para['ordersn'], 'LoanStatus' => '2', 'IsDel' => '0'))->getField('xjnums');
					$days['xjnums']=$xjnums+1;//把续交次数加一
//					把续交次数 和预约还款时间存入数据库
                    $result1 = M('loans_applylist')->where(array('ID' => $para['oid'], 'LoanNo' => $para['ordersn'], 'LoanStatus' => '2', 'IsDel' => '0'))->save($days);
                    $result2 = M('loans_xjapplylist')->where(array('ID' => $result, 'LoanNo' => $para['ordersn'], 'IsDel' => '0'))->save(['PayStatus' => '1', 'Status' => '1']);
                    //创建支付记录
                    $tempData = [
                        'UserID'  => $applyinfo['UserID'],    //用户ID
                        'OrderSn' => $applyinfo['OrderSn'],   //订单单号
                        'LoanNo'  => $applyinfo['LoanNo'],    //申请号
                        'PayType' => 3,      //付款方式  未付款 1支付宝 2微信 3银联 4代付 5线下还款
                        'TradeType'   => 1,  //付款类型 1续借 2线上还款 3放款 4购买商品 5线下还款
                        'PayStatus'   => 1,  //支付状态 0待支付 1已支付
                        'OrderAmount' => (int)$xjdata['TotalMoney'],//还款金额
//                        'OperatorID'  => session('AdminInfo.AdminID'),  //操作者ID
                        'UpdateTime'  => date('Y-m-d H:i:s',time()),      //生成时间
                        'Description' => '用户APP续期',                    //描述
//                       'CollectionAccount' => $_POST['RepaymentAccount'],//收款账户
                    ];
                    $result3 = M('loans_paylist')->add($tempData);
                    if ($result1 && $result2 && $result3) {
//                      $model->commit();//事物提交
                        AjaxJson(0, 1, $data['msg']);
                        die;
                    } else {
//                      $model->rollback();//事物回滚
                        AjaxJson(0, 0, $data['msg']);
                        die;
                    }
                } else {
                	  $result2 = M('loans_xjapplylist')->where(array('ID' => $result, 'LoanNo' => $para['ordersn'], 'IsDel' => '0'))->save(['PayStatus' => '0', 'Status' => '2','jiance' =>$data['msg']]);
					if($result2){
                    AjaxJson(0, 0, $data['msg']);
                    die;
					}
                }
            } else {//微信支付宝操作
                AjaxJson(0, 1, '续借记录提交成功！');
            }
        } else {
            AjaxJson(0, 0, '续借记录提交失败！');
        }
    }
    /**
     * @功能说明: 获取还款支付总金额
     * @传输方式: 私有token,密文提交，明文返回
     * @提交网址: /center/Order/gethkmoney
     * @提交信息：{"token":"3182F49D44F72708AA00041EF2B0E5E1DEDD50FEC4E36FB12C85FFDA80DD","client":"pc","package":"11","version":"1.1","isaes":"1","data":{"oid":"2","ordersn":"12352222"}}
     *   oid 订单的主键id   ordersn订单编号
     * @返回信息: {'result'=>1,'message'=>'登录密码修改成功!'}
     */
    public function gethkpaymoney()
    {
        $para = get_json_data();//接收参数
        $mem = getUserInfo(get_login_info('ID'));
        //校验
        $orderinfo = M(self::T_LOANSAPPLYLIST)->field('ID,OrderSn,YyFkTime,BackM')->where(array('ID' => $para['oid'], 'OrderSn' => $para['ordersn'], 'UserID' => $mem['ID'], 'LoanStatus' => '2', 'IsDel' => '0'))->find();
        if (!$orderinfo) {
            AjaxJson(0, 0, '订单信息不存在！');
        }
        $retdata = array();//返回的详情信息
        $retdata['ID'] = $orderinfo['ID'];
        $retdata['OrderSn'] = $orderinfo['OrderSn'];
        
        //查看是否逾期
        //过了当天夜里24点才算逾期
        $overtimes = date('Y-m-d', strtotime($orderinfo['YyFkTime'])) . ' 23:59:59';
        if ($overtimes < date('Y-m-d H:i:s')) {
            //已经逾期了
            $yuqidata = '';
            $yuqidata = getoverinfos($orderinfo['ID']);
            $retdata['TotalMoney'] = $yuqidata['realtotal'];
        } else {
            //未逾期
            $retdata['TotalMoney'] = $orderinfo['BackM'];
        }
        AjaxJson(0, 1, '恭喜您，数据查询成功！', $retdata, 1, $mem['KEY'], $mem['IV']);
    }

}
